import mysql.connector
from mysql.connector import pooling
import logging
from pathlib import Path
import json
import time

logger = logging.getLogger(__name__)

# 数据库配置
DB_CONFIG = {
    'host': 'localhost',
    'port': 3306,
    'database': 'lora_filter',
    'user': 'root',
    'password': '123456',
    'charset': 'utf8mb4',
    'use_unicode': True,
    'get_warnings': True,
    'pool_name': 'lora_filter_pool',
    'pool_size': 5
}

class DBConnection:
    _pool = None
    
    @classmethod
    def init_pool(cls):
        """初始化连接池"""
        try:
            if not cls._pool:
                cls._pool = mysql.connector.pooling.MySQLConnectionPool(**DB_CONFIG)
                logger.info("数据库连接池初始化成功")
        except Exception as e:
            logger.error(f"初始化数据库连接池失败: {e}", exc_info=True)
            raise
    
    @classmethod
    def get_connection(cls):
        """获取数据库连接"""
        if not cls._pool:
            cls.init_pool()
        return cls._pool.get_connection()
    
    @staticmethod
    def execute(sql, params=None, fetch=False, many=False):
        """执行SQL语句"""
        conn = None
        cursor = None
        try:
            # if many:
            #     logger.info(f"执行SQL(批量): {sql}")
            #     logger.info(f"参数列表: {params}")
            # else:
            #     logger.info(f"执行SQL: {sql}")
            #     logger.info(f"参数: {params}")
            
            conn = DBConnection.get_connection()
            cursor = conn.cursor(dictionary=True)
            
            start_time = time.time()
            
            if many:
                cursor.executemany(sql, params)
            else:
                cursor.execute(sql, params or ())
            
            # 记录执行时间
            elapsed = time.time() - start_time
            # logger.info(f"SQL执行时间: {elapsed:.3f}秒")
            
            if fetch:
                result = cursor.fetchall()
                # logger.info(f"查询返回 {len(result)} 条记录")
                return result
            else:
                conn.commit()
                affected = cursor.rowcount
                # logger.info(f"影响 {affected} 行记录")
                return affected
                
        except Exception as e:
            if conn:
                conn.rollback()
            logger.error(f"执行SQL失败: {sql}, 参数: {params}, 错误: {e}", exc_info=True)
            raise
        finally:
            if cursor:
                cursor.close()
            if conn:
                conn.close() 